<template>
<div class="totalStyle datadictionary">

    <div class="tablestyle">
      <div class="titleStyle">
        <p   class="leftTitle font_w">部门与用户</p>
      </div>
      <div class="bottomBox flex">
          <div class="leftBox">
              <p>山东省港口集团滨州港有限公司</p>
                <div class="treeBox mt-16">
                  <el-tree :load="loadNode" 
                            :props="{ children: 'children',label: 'departmentName'}" 
                            lazy 
                            @node-click="handleNodeClick" >
                  </el-tree>
                </div>
          </div>
          <div class="rightBox"> 
            <div class="partTitle">
              <p class="partName">{{modeldata.table.companyName}}</p>
            </div>
            <div class="searchsize mt-16">
              <el-col  class="searchBox">
                <el-input
                  class="w-10 m-2 mr-16 float-left"
                  v-model="modeldata.searchValue.userSearch"
                  placeholder="请输入姓名/手机号"
                  clearable
                  maxlength="50"
                />
                <el-button type="primary" plain  @click="getUserInfoFun()"
                >查询</el-button>
              </el-col>
            </div>
            <div class="chartstyle">
              <el-table
                :data="modeldata.table.tableData"
                :header-cell-style="{ background: '#F2F5FA' }"     
                border
                style="width: 100%"
              > 
                <el-table-column prop="name"   label="姓名" min-width="10%"/> >
                <el-table-column prop="userName"   label="账号" min-width="10%"/> >
                <el-table-column prop="jobNumber"   label="工号" min-width="10%" />
                <el-table-column prop="phone"  label= '手机号' min-width="10%" />
                <el-table-column prop="deptName"  label= '部门' min-width="10%" />
                <el-table-column  prop="roleNames" label= '功能权限' min-width="20%" />
                <el-table-column  prop="authorityName" label= '数据权限' min-width="20%" />
                <el-table-column label="操作列" width="250">
                  <template #default="scope">
                      <span  class="buttonFun cursor" @click="addrole(scope.$index, scope.row)">功能权限</span>
                      <span  class="buttonFun cursor" @click="addData(scope.$index, scope.row)">数据权限</span>
                      <el-popconfirm 
                          width="520"
                          confirm-button-text="确定"
                          cancel-button-text="取消"
                          @confirm="handleResetpassword(scope.row)"
                          :title="'确定要重置密码吗?重置后密码为Bz' +scope.row.phone+'@'">
                          <template #reference>
                            <span class="buttonFun cursor">重置密码</span>
                          </template>
                        </el-popconfirm>
                        <el-popconfirm 
                          width="520"
                          confirm-button-text="确定"
                          cancel-button-text="取消"
                          @confirm="removerole(scope.row)"
                          title="解绑后，该成员将不能登录系统">
                          <template #reference>
                            <span class="buttonFun cursor">解绑角色</span>
                          </template>
                        </el-popconfirm>
                        <!-- <span  class="buttonFun cursor" @click="removerole(scope.$index, scope.row)">解绑角色</span> -->
                  </template>
                </el-table-column>
                <template #empty>
                    <el-empty v-loading="modeldata.table.tableLoading"></el-empty>
                </template>
              </el-table>
              <div class="demo-pagination-block">
                <el-pagination
                  :pageIndex="modeldata.table.pageIndex"
                  :page-size="modeldata.table.pageSize"
                  :page-sizes="[5, 10, 15, 20]"
                  :small="small"
                  :disabled="disabled"
                  :background="background"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="modeldata.table.total"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                />
              </div>
            </div>
          </div>
      </div>
</div>

  <div class="dialogBox">
       <el-dialog
        ref="editDataRef"
        :model-value="modeldata.dialog.dialogEditVisible"
        :title="modeldata.dialog.title"
        :before-close="closeDialog"
        width="40%"
        :close-on-click-modal ="false"
        draggable
        >
            <div>
                <el-form
                    :model="modeldata.dialog.roleListData"
                  :inline="true"
                  label-width="160px"
                  :rules="modeldata.dialog.rules"
                  ref="addform"
                  require-asterisk-position="left"
                  size="default"
                  scroll-to-error="true"
              >
                  <el-form-item v-if="modeldata.dialog.title == '功能权限'" label="功能权限：" prop="roleList" required>
                      <el-select
                        v-model="modeldata.dialog.roleListData.roleList"
                        :remote="true"
                        placeholder="请选择功能权限"
                        filterable
                        clearable
                        >
                            <el-option v-for="item in modeldata.dropdown.roleList" :key="item.roleId" :label="item.roleName" :value="item.roleId" required>
                            </el-option>
                        </el-select>
                  </el-form-item>
                    <el-form-item  v-if="modeldata.dialog.title == '数据权限'" label="数据权限：" prop="authorityId" required>
                      <el-select
                        v-model="modeldata.dialog.roleListData.authorityId"
                        :remote="true"
                        placeholder="请选择数据权限"
                        filterable
                        clearable
                        >
                            <el-option v-for="item in  modeldata.dropdown.dataAuthorityList" :key="item.id" :label="item.name" :value="item.id" required>
                            </el-option>
                        </el-select>
                  </el-form-item>
              </el-form>
            </div>
            <template #footer>
                    <span class="dialog-footer">
                        <el-button class="btn-mixins-clear-default" @click="closeDialog"
                        >取消</el-button>
                    <el-button type="primary" class="btn-mixins-clear-default" @click="saveData(addform)"
                        >确定</el-button>
                    
                    </span>
            </template>
        </el-dialog>
  </div>
</div>

</template>
<script setup>
// import Dialog from "./edituser.vue";
import { onBeforeMount, watch, getCurrentInstance } from "vue";
import { reactive, ref, markRaw} from "vue";
import { ElMessage, ElMessageBox,ElNotification } from "element-plus";
import { Warning } from "@element-plus/icons-vue";
import { getDepartmentList as getDepartmentList,getChildDepartments as getChildDepartments,getUserCount as getUserCount,
getUsers as getUsers,getRoleList as getRoleList,setUserBindRole as setUserBindRole, getUserInfo as getUserInfo, adminResetPasswords as adminResetPasswords, systemdataauthorityList as systemdataauthorityList,
setUserBindAuthority as setUserBindAuthority, unbindUser as unbindUser} from '@/api/user.js'
import store from '@/store'
// import type Node from 'element-plus/es/components/tree/src/model/node'
const editDataRef = ref('');
const addform = ref('')
const popoverRef = ref()
let modeldata =  reactive({
    dialogimgVisible:false,
    imgurl:'',
    searchValue:{
      userSearch:'',
    },
    dropdown:{
      roleList:[{}],
      dataAuthorityList:[]
    },
    dialog: {
        title:'',
        tableDataId:'',
        roleListData:{
            roleList:'',
            authorityId:''
        },
        rules:{
            roleList:[{ required: true, message: "请选择功能权限", trigger: "Change" }],
            authorityId:[{ required: true, message: "请选择数据权限", trigger: "Change" }],
        },
        dialogEditVisible:false,
        dialogEditDataVisible:false,
    },
    treeData: {
      componyData:[],
      operationVis:'',
      componyNum:''
    },
    table:{
        personNum:'0',
        tableLoading: false,
        componyId:'',
        pageIndex: 1,
        pageSize: 10,
        total:0,
        tableData: [],
    },
    rightList:{
      isbindrole:false
    }
})
const queryTableData = (deptId) => {
  modeldata.table.tableLoading = true;
  // let obj = JSON.parse(JSON.stringify(modeldata.searchValue))
  let obj = {}
  obj.pageIndex = modeldata.table.pageIndex
  obj.pageSize = modeldata.table.pageSize
  obj.deptId = deptId
  getUsers(obj)
    .then((res)=>{
      modeldata.table.tableLoading = false;
      if(res.code === 200){
        //console.log(res)
         let data = res.body;
          modeldata.table.tableData=data&&data?data.records:[];
          modeldata.table.total = data&&data.total?data.total:0;
          modeldata.table.personNum = data&&data.total?data.total:0;
        }else{
            ElNotification({
              title: '提示',
              message: res.message?res.message:'服务器异常',
              type: 'warning',
            })
            if(res.code === 100007 ||  res.code === 100008 ||  res.code === 100011){
                    store.dispatch('app/logout')
                }
        }
    })
    .catch(()=>{})
};
const getDepartmentListFun = ()=>{
  getDepartmentList().then((res)=>{
    if(res.code === 200){
        modeldata.treeData.componyData = res.body;
        modeldata.table.companyName = modeldata.treeData.componyData[0].departmentName;
        modeldata.table.componyId = modeldata.treeData.componyData[0].deptId;
        // queryTableData(modeldata.table.componyId)
    }else{
        ElNotification({
              title: '提示',
              message: res.message?res.message:'服务器异常',
              type: 'warning',
            })
            if(res.code === 100007 ||  res.code === 100008 ||  res.code === 100011){
                    store.dispatch('app/logout')
                }
    }
  })
}
const getUserCountFun = () => {
  getUserCount(-2628703926362683089).then((res)=>{
    if(res.code === 200){
        modeldata.treeData.componyNum = res.body;
    }else{
        ElNotification({
              title: '提示',
              message: res.message?res.message:'服务器异常',
              type: 'warning',
            })
            if(res.code === 100007 ||  res.code === 100008 ||  res.code === 100011){
                    store.dispatch('app/logout')
                }
    }
  })
}
const getRoleListFun = () => {
    getRoleList().then((res)=>{
        if(res.code === 200){
            modeldata.dropdown.roleList = res.body;
        }else{
            ElNotification({
                title: '提示',
                message: res.message?res.message:'服务器异常',
                type: 'warning',
                })
                if(res.code === 100007 ||  res.code === 100008 ||  res.code === 100011){
                        store.dispatch('app/logout')
                    }
        }
    })
}
// const getright= () => {
//   let menulist_ =  JSON.parse(localStorage.getItem('userData')).menuTrees ;
//   //console.log(menulist_)
//   let index = menulist_.findIndex((item)=>  {return item.menuName === '系统管理'});
//   if(index>-1){
//     let index01 = menulist_[index].children.findIndex((item)=>  {return item.menuName === '部门与用户'})
//     if (index01 > -1) {
//        menulist_[index].children[index01].right.forEach((item) => {
//          switch (item) {
//            case 'bindrole':
//                   modeldata.rightList.isbindrole = true;
//             break;
//          }
//        })
//     }
//   }
// }
const systemdataauthorityListFun = () => {
    let obj={
        name: '',
        current:1,
        size:-1
    }
    console.log(obj)
    systemdataauthorityList(obj,obj.current,obj.size).then((res)=>{
        if(res.code === 200){
             let data = res.body;
            modeldata.dropdown.dataAuthorityList = data&&data?data.records:[];
            console.log(modeldata.dropdown.dataAuthorityList)
        }else{
            ElNotification({
                title: '提示',
                message: res.message?res.message:'服务器异常',
                type: 'warning',
                })
                if(res.code === 100007 ||  res.code === 100008 ||  res.code === 100011){
                        store.dispatch('app/logout')
                    }
        }
    })
}
onBeforeMount(()=>{
systemdataauthorityListFun()
  getUserCountFun()
  getRoleListFun()
//   getright();
  
})
const loadNode = (node,resolve) => {
    //console.log(node)
    if (node.level === 0) {
      getDepartmentList().then((res)=>{
            if(res.code === 200){
                resolve(res.body);
            }else{
                ElNotification({
                    title: '提示',
                    message: res.message?res.message:'服务器异常',
                    type: 'warning',
                    })
                    if(res.code === 100007 ||  res.code === 100008 ||  res.code === 100011){
                            store.dispatch('app/logout')
                        }
            }
      })
    }else{
        getChildDepartments(node.data.deptId).then((res)=>{
            if(res.code === 200){
                resolve(res.body);
            }else{
                ElNotification({
                    title: '提示',
                    message: res.message?res.message:'服务器异常',
                    type: 'warning',
                    })
                    if(res.code === 100007 ||  res.code === 100008 ||  res.code === 100011){
                            store.dispatch('app/logout')
                        }
            }
      })
    }

}
//查询
const getUserInfoFun = () =>{
    let value = modeldata.searchValue.userSearch
    getUserInfo(value).then((res)=>{
      modeldata.table.tableLoading = false;
      if(res.code === 200){
        //console.log(res)
          let data = res.body;
          modeldata.table.tableData=data?data:[];
          modeldata.table.total = modeldata.table.tableData.length;
        }else{
            ElNotification({
                title: '提示',
                message: res.message?res.message:'服务器异常',
                type: 'warning',
                })
                if(res.code === 100007 ||  res.code === 100008 ||  res.code === 100011){
                        store.dispatch('app/logout')
                    }
        }
    })
}
/**
 * 显示部门数据
 */
const handleNodeClick = (data)=>{
    //console.log(data)
    modeldata.table.companyName = data.departmentName;
    modeldata.table.componyId = data.deptId
    modeldata.table.tableData=[];
    modeldata.table.total = 0;
    modeldata.table.personNum = 0;
    queryTableData(data.deptId)
}
//切换一页显示多少条数据
const handleSizeChange = (val) => {
    modeldata.table.pageSize = val;
    queryTableData(modeldata.table.componyId)
};
// 点击跳转到第几页
const handleCurrentChange = (val) => {
  modeldata.table.pageIndex = val;
  queryTableData(modeldata.table.componyId)
};

//绑定角色
const addrole = (index, row) => {
    modeldata.dialog.tableDataId = row.userId;
    modeldata.dialog.roleListData.roleList  = row.roleId;
    modeldata.dialog.dialogEditVisible = true;
     modeldata.dialog.title = '功能权限'
};
//数据权限
const addData = (index, row)=>{
    modeldata.dialog.tableDataId = row.userId;
    modeldata.dialog.roleListData.roleList  = row.roleId;
    modeldata.dialog.dialogEditVisible = true;
    modeldata.dialog.title = '数据权限'

}
// 关闭弹框
const closeDialog = () => {
  addform.value.resetFields();
  modeldata.dialog.dialogEditVisible = false;
};
//表单提交
const saveData = (addform) => {
    if (!addform) return;
  addform.validate(async (valid) => {
    if (valid) {
      let obj = {
          roleIds:modeldata.dialog.roleListData.roleList,
          userId:modeldata.dialog.tableDataId,
          authorityId:modeldata.dialog.roleListData.authorityId,
      }
      if(modeldata.dialog.title == '功能权限'){
                setUserBindRole(obj).then((res)=>{
                    if(res.code ===200){
                        closeDialog()
                        queryTableData(modeldata.table.componyId)
                    }else{
                        ElNotification({
                            title: '提示',
                            message: res.message?res.message:'服务器异常',
                            type: 'warning',
                        })
                        if(res.code === 100007 ||  res.code === 100008 ||  res.code === 100011){
                                store.dispatch('app/logout')
                            }
                    }
                })
      }else{
          setUserBindAuthority(obj).then((res)=>{
                    if(res.code ===200){
                        closeDialog()
                        queryTableData(modeldata.table.componyId)
                    }else{
                        ElNotification({
                            title: '提示',
                            message: res.message?res.message:'服务器异常',
                            type: 'warning',
                        })
                        if(res.code === 100007 ||  res.code === 100008 ||  res.code === 100011){
                                store.dispatch('app/logout')
                            }
                    }
                })
      }

    } else {
      return false;
    }
  });
}
//重置密码
const handleResetpassword = (row)=>{
  adminResetPasswords(row.id).then((res)=>{
    if(res.code === 200){
        ElNotification({
              title: '成功',
              message: '重置密码成功',
              type: 'success',
            })
    }else{
        ElNotification({
              title: '提示',
              message: res.message?res.message:'服务器异常',
              type: 'warning',
            })
            if(res.code === 100007 ||  res.code === 100008 ||  res.code === 100011){
                    store.dispatch('app/logout')
                }
    }
  })
}
const removerole =(row) =>{
    unbindUser(row.id).then((res)=>{
    if(res.code === 200){
         queryTableData();
        ElNotification({
              title: '成功',
              message: '解除绑定成功',
              type: 'success',
            })
    }else{
        ElNotification({
              title: '提示',
              message: res.message?res.message:'服务器异常',
              type: 'warning',
            })
            if(res.code === 100007 ||  res.code === 100008 ||  res.code === 100011){
                    store.dispatch('app/logout')
                }
    }
  })
}
</script>
<style  lang = 'less' scoped>
.datadictionary{
    .searchBox{
        :deep(.el-input){
            width: 200px;
        }
    }
    :deep(.el-table--fit){
      height:100%;
    }
    :deep(.el-table__body-wrapper) {
      overflow-y: auto;
    }
    .tablestyle {
      position: relative;
      :deep(.el-table__header thead tr) {
        background-color: rgba(64, 158, 255, 0.1);
      }
      :deep(.el-col-3 ){
        max-width: none;
      }
    }

    .demo-pagination-block {
      margin-top: 16px;
      position: absolute;
      bottom: 32px;
      right: 32px;
    }
    .dialogBox{
          :deep(.el-form--inline .el-form-item){
              width: 100%;
          }
          :deep(.el-input){
                width: 100%;
            }
          :deep(.el-select){
            width: 100%;
          }
          :deep(.el-dialog__body){
            padding-right: 160px;
          }
          :deep(.el-form-item--default .el-form-item__content){
            width: calc(100% - 80px);
        }
          :deep(.el-dialog__header) {
            border-bottom: 1px solid #cccccc;
            padding: 16px;
            margin-right: 0;
            display: flex;
            justify-content: space-between;
            align-items: center;
          }
          :deep(.el-dialog__title) {
            color: #1C222C;
            font-size: 20px;
            width: 100px;
          }
          :deep(.el-dialog__headerbtn ){
            position: static;
            top: 0px;
            right: 0;
            padding: 0;
            width: auto;
            height: auto;
          }
    }

    .totalStyle{
        height: 100%;
    }
    .bottomBox{
      width: 100%;
      padding: 0;
    }
    .rightBox{
      width: 80%;
      padding: 16px;
      .chartstyle {
        height: calc(100% - 170px);
      }
    }
    .leftBox{
      width: 20%;
      padding: 16px;
      border-right: 1px solid #DADFE6;
      height: 100%;
      overflow-y: auto;
      .addPart{
        width: 100%;
      }
    }
    .partTitle{
      height: 32px;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
    .custom-tree-node{
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
}
  :deep(.el-tree-node__label){
    width: 100%;
  }
}
</style>